<template>
  <div class="content">
    <div class="header_box">
      <div class="header_left">账户列表</div>
      <div class="header_right">
        <el-form :inline="true" :model="searFrom" class="form_box">
          <el-form-item>
            <el-input
              v-model="searFrom.username"
              placeholder="企业账户"
              style="width: 200px"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="searFrom.billingMode"
              placeholder="计费模式"
              style="width: 200px"
              clearable
            >
              <el-option label="手动" value="manual" />
              <el-option label="自动" value="automatic" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="searFrom.userRole"
              placeholder="待授权订单"
              style="width: 200px"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="init">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toInfo">新增账户</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{ background: '#fafbfc', color: '#bbbcc3' }"
      max-height="500"
    >
      <el-table-column type="index" :index="indexMethod" />
      <el-table-column prop="username" label="企业账户名">
        <template #default="{ row }">
          <div class="avatar_box">
            {{ row.username }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="billingMode" label="计费模式">
        <template #default="{ row }">
          <el-select
            v-model="row.billingMode"
            placeholder="选择计费模式"
            @change="updateBillingMode(row)"
          >
            <el-option label="手动" value="manual" />
            <el-option label="自动" value="automatic" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="orderNumber" label="待授权订单">
        <template #default="{ row }">
          <el-button type="text" @click="viewOrderDetails(row)">
            {{ row.orderNumber }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="pricingMode" label="单价设定">
        <template #default="{ row }">
          <el-button type="text" @click="openPricingDialog">设定价格</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="特殊定制">
        <template #default="{ row }">
          <el-button type="text" @click="openCustomizationDialog(row)"
            >定制</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="isActive" label="状态">
        <template #default="{ row }">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="row.isActive"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" />
      <el-table-column prop="updatedAt" label="更新时间" />
      <el-table-column label="交易日志">
        <template #default="{ row }">
          <el-button type="text" @click="viewTransactionLog(row)"
            >查看日志</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="聊天">
        <template #default="{ row }">
          <el-button type="text" @click="startChat(row)">开始聊天</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="balance" label="余额" />
      <el-table-column label="充值">
        <template #default="{ row }">
          <el-button type="text" @click="recharge(row)">充值</el-button>
        </template>
      </el-table-column>
      <el-table-column label="扣费">
        <template #default="{ row }">
          <el-button type="text" @click="deduct(row)">扣费</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <div class="icon_content">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="编辑"
              placement="top-start"
            >
              <div class="icon_box">
                <el-icon @click="edit(row)" size="20" color="#71778d"
                  ><EditPen
                /></el-icon>
              </div>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="删除"
              placement="top-start"
            >
              <div class="icon_box_d">
                <el-icon @click="remove(row)" size="20" color="#71778d"
                  ><Remove
                /></el-icon>
              </div>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page_box">
      <el-pagination
        v-model:current-page="searFrom.pageNo"
        v-model:page-size="searFrom.pageSize"
        :page-sizes="[10, 50, 100, 150]"
        :small="small"
        :disabled="false"
        :background="true"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog v-model="dialogVisible" title="查看订单" width="50%">
      <el-table :data="deviceList" style="width: 100%">
        <el-table-column prop="deviceName" label="产品" />
        <el-table-column prop="ip" label="IP" />
        <el-table-column prop="node" label="节点" />
        <el-table-column prop="proxy" label="代理信息" />
        <!-- <el-table-column prop="status" label="状态" /> -->
        <!-- 可以根据需要添加更多字段 -->
      </el-table>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="customizationDialogVisible" title="定制" width="70%">
      <el-form :model="customizationForm" label-width="120px">
        <el-form-item label="产品">
          <el-select
            v-model="customizationForm.productSeries"
            multiple
            filterable
            placeholder="选择产品"
            style="width: 100%"
          >
            <el-option
              v-for="product in productList"
              :key="product.value"
              :label="product.label"
              :value="product.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="节点组/节点">
          <el-input
            v-model="customizationForm.nodeGroup"
            placeholder="输入节点组/节点"
          />
        </el-form-item>
        <el-form-item label="IP段或具体IP">
          <el-input
            v-model="customizationForm.ipRange"
            placeholder="输入IP段或具体IP"
          />
        </el-form-item>
        <el-form-item label="地区配置">
          <el-input
            v-model="customizationForm.regionConfig"
            placeholder="输入地区配置"
          />
        </el-form-item>
        <el-form-item label="时长">
          <el-input
            v-model="customizationForm.duration"
            placeholder="输入时长"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="customizationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCustomization">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="authorizedDevicesDialogVisible"
      title="已授权设备"
      width="50%"
    >
      <el-table :data="authorizedDeviceList" style="width: 100%">
        <el-table-column prop="deviceName" label="设备名称" />
        <el-table-column prop="deviceType" label="设备类型" />
        <el-table-column prop="status" label="状态" />
        <!-- 可以根据需要添加更多字段 -->
      </el-table>
      <template #footer>
        <el-button @click="authorizedDevicesDialogVisible = false"
          >关闭</el-button
        >
      </template>
    </el-dialog>
    <el-dialog
      v-model="transactionLogDialogVisible"
      title="交易日志"
      width="70%"
    >
      <el-table :data="transactionLogData" style="width: 100%">
        <el-table-column prop="date" label="日期" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="amount" label="金额" />
        <el-table-column prop="status" label="状态" />
        <!-- 可以根据需要添加更多字段 -->
      </el-table>
      <template #footer>
        <el-button @click="transactionLogDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="chatDialogVisible" title="聊天记录" width="70%">
      <div class="chat-container">
        <div
          v-for="(chat, index) in chatHistory"
          :key="index"
          :class="[
            'chat-message',
            chat.isUser ? 'user-message' : 'other-message',
          ]"
        >
          <span class="chat-timestamp">{{ chat.timestamp }}</span>
          <p class="chat-text">{{ chat.message }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="chatDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="pricingDialogVisible" title="单价设定" width="70%">
      <el-form label-width="120px">
        <el-form-item label="选择国家">
          <el-select
            v-model="selectedCountry"
            placeholder="选择国家"
            style="width: 100%"
            @change="filterProductsByCountry"
          >
            <el-option
              v-for="country in countryList"
              :key="country.value"
              :label="country.label"
              :value="country.value"
            />
          </el-select>
        </el-form-item>
        <el-table :data="filteredProductList" style="width: 100%">
          <el-table-column prop="label" label="产品名称" />
          <el-table-column label="价格">
            <template #default="{ row }">
              <el-input
                v-model="row.price"
                placeholder="输入价格"
                style="width: 100px"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <el-button @click="pricingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePricing">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { defineOptions, ref, onBeforeMount } from "vue";
import * as userApi from "../../../api/project1/user/user.js";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
defineOptions({ name: "UserList" });

let tableData = ref([
  {
    username: "dayu",
    billingMode: "manual",
    pricingMode: "standard",
    email: "2045279876@qq.com",
    phone: "18946873767",
    address: "深圳市宝安区",
    createdAt: "2021-01-05 9:00:00",
    orderNumber: "ORD123456",
    balance: 100,
  },
]);

let searFrom = ref({
  username: "",
  email: "",
  password: "",
  billingMode: "",
  pricingMode: "",
  phone: "",
  isActive: 1,
  userRole: "",
  pageNo: 1,
  pageSize: 10,
});

let total = ref(0);

let roleLabels = ref({
  0: "后台超级管理员",
  1: "后台管理员",
  2: "后台用户",
  3: "小程序用户",
});

const router = new useRouter();

let dialogVisible = ref(false);
let deviceList = ref([]);
let customizationDialogVisible = ref(false);
let customizationForm = ref({
  productSeries: [],
  nodeGroup: "",
  ipRange: "",
  regionConfig: "",
  duration: "",
});

let authorizedDevicesDialogVisible = ref(false);
let authorizedDeviceList = ref([]);

let transactionLogDialogVisible = ref(false);
let chatDialogVisible = ref(false);
let chatHistory = ref([
  { message: "你好", timestamp: "2023-10-01 10:00:00", isUser: false },
  {
    message: "请问有什么可以帮助您？",
    timestamp: "2023-10-01 10:05:00",
    isUser: true,
  },
  // 添加更多模拟数据
]);

let transactionLogData = ref([
  {
    date: "2023-10-01",
    description: "购买服务",
    amount: "¥100",
    status: "成功",
  },
  { date: "2023-10-02", description: "退款", amount: "¥50", status: "失败" },
  // 添加更多模拟数据
]);

let productList = ref([
  { label: "产品A", value: "productA" },
  { label: "产品B", value: "productB" },
  { label: "产品C", value: "productC" },
  // 添加更多产品
]);

let pricingDialogVisible = ref(false);
let selectedCountry = ref(null);
let countryList = ref([
  { label: "中国", value: "china" },
  { label: "美国", value: "usa" },
  { label: "英国", value: "uk" },
  // 添加更多国家
]);

let filteredProductList = ref([]);
let isInitialized = ref(false);

const init = async () => {
  try {
    const res = await userApi.page(searFrom.value);
    const { records } = res;
    tableData.value = records;
    total.value = res.total;
  } catch (error) {
    console.error("初始化数据时出错:", error);
    ElMessage.error("加载数据失败，请稍后重试");
  }
};
const handleStatusChange = async (row) => {
  if (!isInitialized.value) {
    return;
  }
  try {
    // 假设有一个 API 方法来更新用户的状态
    await userApi.updateStatus(row);
    ElMessage.success("状态更新成功");
  } catch (error) {
    ElMessage.error("状态更新失败，请重试");
  }
};

const toInfo = () => {
  router.push({
    name: "userInfo",
  });
};

const showDevices = (row) => {
  // 模拟请求后端获取设备列表
  deviceList.value = [
    { deviceName: "设备1", deviceType: "类型A", status: "正常" },
    { deviceName: "设备2", deviceType: "类型B", status: "异常" },
    // 添加更多模拟数据
  ];
  dialogVisible.value = true;
};

const showAuthorizedDevices = (row) => {
  // 模拟请求后端获取已授权设备列表
  authorizedDeviceList.value = [
    { deviceName: "设备A", deviceType: "类型1", status: "正常" },
    { deviceName: "设备B", deviceType: "类型2", status: "异常" },
    // 添加更多模拟数据
  ];
  authorizedDevicesDialogVisible.value = true;
};

const viewTransactionLog = (row) => {
  // 在这里实现查看交易日志的逻辑
  console.log("查看交易日志:", row);
  transactionLogDialogVisible.value = true;
};

const startChat = (row) => {
  // 模拟获取聊天记录
  chatHistory.value = [
    { message: "你好", timestamp: "2023-10-01 10:00:00", isUser: false },
    {
      message: "请问有什么可以帮助您？",
      timestamp: "2023-10-01 10:05:00",
      isUser: true,
    },
    // 添加更多模拟数据
  ];
  chatDialogVisible.value = true;
};

const openCustomizationDialog = (row) => {
  // 在这里实现打开定制对话框的逻辑
  console.log("打开定制对话框:", row);
  customizationDialogVisible.value = true;
};

const saveCustomization = () => {
  // 在这里实现保存定制配置的逻辑
  console.log("保存定制配置:", customizationForm.value);
  customizationDialogVisible.value = false;
};

const filterProductsByCountry = () => {
  // 根据选择的国家过滤产品列表
  // 这里假设每个产品都有一个国家属性
  filteredProductList.value = productList.value.map((product) => ({
    ...product,
    price: 0, // 初始化价格为0
  }));
};

const savePricing = () => {
  // 保存定价逻辑
  console.log("保存定价:", filteredProductList.value);
  pricingDialogVisible.value = false;
};

const openPricingDialog = () => {
  pricingDialogVisible.value = true;
  filterProductsByCountry();
};

const updateBillingMode = async (row) => {
  try {
    // 假设有一个 API 方法来更新用户的计费模式
    await userApi.updateBillingMode(row);
    ElMessage.success("计费模式更新成功");
  } catch (error) {
    ElMessage.error("更新失败，请重试");
  }
};

const viewOrderDetails = (row) => {
  // 在这里实现查看订单详情的逻辑
  console.log("查看订单详情:", row);
  // 设置设备列表为订单详情
  deviceList.value = [
    {
      deviceName: "产品1",
      deviceType: "类型A",
      status: "正常",
      ip: "192.168.1.1",
      node: "节点1",
      proxy: "代理信息1",
    },
    {
      deviceName: "产品2",
      deviceType: "类型B",
      status: "异常",
      ip: "192.168.1.2",
      node: "节点2",
      proxy: "代理信息2",
    },
    // 添加更多模拟数据
  ];
  dialogVisible.value = true;
};

const recharge = (row) => {
  // 在这里实现充值逻辑
  console.log("充值操作:", row);
  // 例如，打开充值对话框或进行API调用
};

const deduct = (row) => {
  // 在这里实现扣费逻辑
  console.log("扣费操作:", row);
  // 例如，打开扣费对话框或进行API调用
};

onBeforeMount(() => {
  // 初始化数据
  init().then(() => {
    isInitialized.value = true;
  });
});
</script>
<style lang="less" scoped>
.header_left {
  border-radius: 15px 0px 0px 0px;
  font-weight: 800;
}
.header_right {
  background-color: #ffffff;
  justify-content: flex-end;
  border-radius: 0px 15px 0px 0px;
}
:deep(.form_box) {
  width: 80%;
  height: 40%;
  margin: 0px;
  display: flex;
  justify-content: flex-end;
}
.chat-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.chat-message {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.user-message {
  align-self: flex-end;
  background-color: #d1e7dd;
  border-radius: 15px 15px 0 15px;
}

.other-message {
  align-self: flex-start;
  background-color: #f1f1f1;
  border-radius: 15px 15px 15px 0;
}

.chat-timestamp {
  font-size: 0.7em;
  color: #888;
  margin-bottom: 2px;
}

.chat-text {
  margin: 0;
  padding: 8px 12px;
  font-size: 0.9em;
}
</style>